package com.m7788.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.DownloadManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

/**
 * 文件操作类
 * @Description: 文件操作类

 * @FileName: FileUtil.java 

 * @Package com.device.photo 

 * @Author Hanyonglu

 * @Date 2012-5-10 下午01:37:49 

 * @Version V1.0
 */
public class FileUtil {
    public FileUtil() {
        // TODO Auto-generated constructor stub
    }
    
    /**
     * InputStream to byte
     * @param inStream
     * @return
     * @throws Exception
     */
    public byte[] readInputStream(InputStream inStream) throws Exception { 
        byte[] buffer = new byte[1024]; 
        int len = -1; 
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        
        while ((len = inStream.read(buffer)) != -1) { 
            outStream.write(buffer, 0, len); 
        }
        
        byte[] data = outStream.toByteArray(); 
        outStream.close(); 
        inStream.close();
        
        return data; 
   }

    public void downFile(Context context,final String webUrl, final String dirPath,
                         final String fileName){
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(webUrl));
        //指定下载路径和下载文件名
        request.setDestinationInExternalPublicDir(dirPath, fileName);
        //获取下载管理器
        DownloadManager downloadManager= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载任务加入下载队列，否则不会进行下载
        downloadManager.enqueue(request);
    }
    
   /**
    * Byte to bitmap
    * @param bytes
    * @param opts
    * @return
    */
   public Bitmap getBitmapFromBytes(byte[] bytes, BitmapFactory.Options opts) {
       if (bytes != null){
           if (opts != null){ 
               return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,opts); 
           }
           else{
               return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
           }
       }
       
       return null; 
   }

    /**
     * 创建SD目录
     *
     * @param SDPath
     * @return
     */
    public static File createSDDir(String SDPath) {
        File dir = new File(SDPath);
        dir.mkdir();
        return dir;
    }

    /**
     * 判断文件是否存在
     *
     * @param SDPath
     * @param filename
     * @return
     */
    public static boolean isFileExist(String SDPath, String filename) {
        File file = new File(SDPath + filename);
        return file.exists();
    }

    /**
     * 判断路径是否存在
     *
     * @param SDPath
     * @return
     */
    public static boolean isPathExist(String SDPath) {
        File file = new File(SDPath);
        return file.exists();
    }

    /**
     * 获取网络上的图片流
     *
     * @author lhy
     * @return
     * @throws IOException
     */
    public static InputStream getInputStreamFromInternet(String image) throws IOException {
        InputStream inputStream = null;
//		Bitmap bitmap = null;
        String URL_PATH = null;
        // 头像图片的网络地址
        URL_PATH = image;
        URL url = new URL(URL_PATH); // 服务器地址
        if (url != null) {
            // 打开连接

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(8000);// 设置网络连接超时的时间为3秒
            httpURLConnection.setRequestMethod("GET"); // 设置请求方法为GET
            httpURLConnection.setDoInput(true); // 打开输入流
            int responseCode = httpURLConnection.getResponseCode(); // 获取服务器响应值
            if (responseCode == HttpURLConnection.HTTP_OK) { // 正常连接
                inputStream = httpURLConnection.getInputStream(); // 获取输入流

            }
        }
        return inputStream;
    }

    /**
     *
     * 在sd卡的路径下创建文件
     *
     * @param SDPath
     * @param filename
     * @return
     * @throws IOException
     */
    public static File createSDFile(String SDPath, String filename) throws IOException {
        File file = new File(SDPath + filename);
        file.createNewFile();
        return file;
    }

    /**
     * 将一个InputStream里的数据写进SD卡
     *
     * @param path
     * @param fileName
     * @param inputstream
     * @return
     * @throws IOException
     */
    public static File inputSD(String path, String fileName, InputStream inputstream) throws IOException {
        File dir=new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(path + fileName);

        file.createNewFile();
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap mBitmap = null;
        mBitmap = BitmapFactory.decodeStream(inputstream);
        if (mBitmap != null) {
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
            try {
                fOut.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
    /**
     * 获取网络上的图片Bitmap
     *
     * @author lhy
     * @return
     * @throws IOException
     */
    public static Bitmap getImageViewFromInternet(String image)throws IOException {
        InputStream inputStream = null;
        Bitmap bitmap = null;
        String URL_PATH = null;
        // 头像图片的网络地址
        URL_PATH = image;
        URL url = new URL(URL_PATH); // 服务器地址
        if (url != null) {
            // 打开连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);// 设置网络连接超时的时间为3秒
            httpURLConnection.setRequestMethod("GET"); // 设置请求方法为GET
            httpURLConnection.setDoInput(true); // 打开输入流
            int responseCode = httpURLConnection.getResponseCode(); // 获取服务器响应值
            if (responseCode == HttpURLConnection.HTTP_OK) { // 正常连接
                inputStream = httpURLConnection.getInputStream(); // 获取输入流
            }
        }
        bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }


    /**
     * 删除指定文件或目录
     * @param pathName
     */
    public void deleteFile(String pathName) {
        File file = new File(pathName);
        File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
        file.renameTo(to);
        deleteFile(to);
    }
    /**
     * 删除指定文件或目录
     * @param file
     */
    public void deleteFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            if (file.isFile()) { // 判断是否是文件
                file.delete(); // delete()方法 你应该知道 是删除的意思;
            } else if (file.isDirectory()) { // 否则如果它是一个目录
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                    this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
                }
            }
            file.delete();
        }
    }
}